import React from "react";

class Charts extends React.Component {
  constructor(props) {
    super(props);
    this.chart = null;
    this.bindEvent = null;
  }

  componentDidMount() {
    const { onReady, onRef } = this.props;
    this.drawChart();
    if (onReady) {
      onReady(this.chart);
    }
    onRef && onRef(this);
  }

  componentDidUpdate() {
    const { onReady } = this.props;
    this.drawChart();
    if (onReady) {
      onReady(this.chart);
    }
  }

  componentWillUnmount() {
    this.chart.dispose();
  }

  drawChart() {
    const node = this.refs.chart;
    const { options, clickEcharts } = this.props;
    const chart = echarts.getInstanceByDom(node);
    if (!chart) {
      this.chart = echarts.init(node, "helios");
    }
    if (options) {
      this.chart.setOption(options);
      if (clickEcharts && this.bindEvent !== clickEcharts) {
        this.bindEvent && this.chart.off('click', this.bindEvent);
        this.chart.on('click', this.bindEvent = clickEcharts);
      }
    }
  }

  //把组件实例挂载到容器组件或者其他组件，可以直接调用这个函数重置图表
  resetChartOption(option) {
    this.chart.setOption(option);
  }

  render() {
    const { width, height, style, options, onReady, ...props } = this.props;
    return (
      <div
        ref="chart"
        style={{ height, width, ...style }}
        {...props}>
      </div>
    );
  }
}

Charts.propTypes = {
  options: React.PropTypes.object,
  onReady: React.PropTypes.func, //获取chart实例，绑定交互事件
  height: React.PropTypes.number,
  width: React.PropTypes.number,
  clickEcharts: React.PropTypes.any,
  onRef: React.PropTypes.any
};

Charts.defaultProps = {
  height: 400
};

export default Charts;
